package com.cloud.train.member.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.cloud.train.common.req.MemberTicketReq;
import com.cloud.train.common.resp.PageResp;
import com.cloud.train.common.util.SnowUtil;
import com.cloud.train.member.domain.Ticket;
import com.cloud.train.member.domain.TicketExample;
import com.cloud.train.member.mapper.TicketMapper;
import com.cloud.train.member.req.TicketQueryReq;
import com.cloud.train.member.req.TicketSaveReq;
import com.cloud.train.member.resp.TicketQueryResp;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.seata.core.context.RootContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class TicketService {
    @Resource
    private TicketMapper ticketMapper;
    public PageResp<TicketQueryResp> queryList(TicketQueryReq req) {
        TicketExample ticketExample = new TicketExample();
        TicketExample.Criteria criteria = ticketExample.createCriteria();
        if (ObjectUtil.isNotNull(req.getMemberId())) {
            criteria.andMemberIdEqualTo(req.getMemberId());
        }
        PageHelper.startPage(req.getPage(),req.getSize());
        List<Ticket> tickets = ticketMapper.selectByExample(ticketExample);
        PageInfo<Ticket> ticketPageInfo = new PageInfo<>(tickets);
        List<TicketQueryResp> ticketQueryResps = BeanUtil.copyToList(tickets, TicketQueryResp.class);
        PageResp<TicketQueryResp> ticketQueryRespPageResp = new PageResp<>();
        ticketQueryRespPageResp.setTotal(ticketPageInfo.getTotal());
        ticketQueryRespPageResp.setList(ticketQueryResps);
        return ticketQueryRespPageResp;
    }

    public void save(MemberTicketReq req) throws Exception{
        log.info("seata全局事务ID,save:{}", RootContext.getXID());
        DateTime dateTime = new DateTime();
        Ticket ticket = BeanUtil.copyProperties(req, Ticket.class);
        ticket.setCreateTime(dateTime);
        ticket.setUpdateTime(dateTime);
        ticket.setId(SnowUtil.getSnowflakeNextId());
        ticketMapper.insert(ticket);
//        if (1 == 1){
//            throw new Exception("测试错误");
//        }
    }
}
